import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { fi } from 'element-plus/es/locale'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard',
  },
  {
    path: '/login',
    name: 'loginPage',
    meta: {
      title: '登录',
    },
    component: () => import('@/views/login/index.vue'),
  },
  {
    path: '/404',
    name: '404',
    meta: {
      title: '404',
    },
    component: () => import('@/views/error/404.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由白名单，无需登录和权限就能访问
const whiteLink = ['/login']
// 异步路由加载标志
let asyncMenusLoaded = false
// 路由拦截
router.beforeEach(async (to, from) => {
  const token = localStorage.getItem('user_token')
  if (whiteLink.includes(to.path)) {
    // 在路由白名单中
    if (to.path === '/login' && token) {
      // 已登录状态访问登录页会跳转首页
      ElMessage({
        type: 'warning',
        message: '已登录，返回首页',
      })
      return { path: '/dashboard' }
    }
  } else if (token) {
    // 已登录
    const userStore = useUserStore()
    if (userStore.menus.length === 0 && !asyncMenusLoaded) {
      // 将local storage中的user info写入store
      const userInfoCache = localStorage.getItem('user_info')
      if (userInfoCache) {
        userStore.setUserInfo(JSON.parse(userInfoCache))
      }
      await userStore.getUserMenu()
      // console.log(router.getRoutes())
      asyncMenusLoaded = true
      return { ...to, replace: true }
    }
  } else {
    // 未登录，返回登录页
    ElMessage({
      type: 'warning',
      message: '未登录，返回登录页',
    })
    return { path: '/login' }
  }
})

export default router
